class Activity < ActiveRecord::Base
  belongs_to :project
  belongs_to :responsible, :class_name => "User", :foreign_key => "responsible_id"
  belongs_to :milestone
  
  has_many :comments, :as => :commentable
  
  accepts_nested_attributes_for :comments
  
  named_scope :open, :conditions => ["completed_at IS NULL"]
  named_scope :recent, :conditions => ["created_at BETWEEN ? AND ?", Date.today, Date.yesterday]
  named_scope :completed, :conditions => ["completed_at IS NOT NULL"]
  
  
  def completed?
    return !completed_at.nil?
  end
  #before_update :was_completed?
  
  def was_completed?
    puts completed_at
    if completed_at_changed?
      if completed_at
        self.completed_at = Date.now
      end
    end
  end
  
  has_many :logs, :as => :loggable
  
  after_create :log_creation
  after_update :log_update
  after_destroy :log_delete
  
  def log_creation
    logs.new(:project => project, :action => "created", :user_id => Thread.current[:user_id]).save
  end
  
  def log_update
    if completed_at_changed?
      if completed_at.nil?
        logs.new(:project => project, :action => "reopened", :user_id => Thread.current[:user_id]).save
      else
        logs.new(:project => project, :action => "concluded", :user_id => Thread.current[:user_id]).save
      end
    else
      logs.new(:project => project, :action => "changed", :user_id => Thread.current[:user_id]).save
    end
  end
  
  def log_delete
    logs.new(:project => project, :action => "deleted", :user_id => Thread.current[:user_id]).save
  end
end